// component/ui/z-collapse/index.js
const path = '../z-collapses/z-collapses'

Component({
  relations: {
    [path]: {
      type: 'ancestor',
      linked: function (target) {},
      linkChanged: function (target) {},
      unlinked: function (target) {}
    }
  },
  /**
   * 组件的配置
   */
  options: {
    multipleSlots: true,
    styleIsolation: 'isolated',
    pureDataPattern: /^_/,
  },
  /**
   * 组件的属性列表
   */
  properties: {
    name: {
      type: String,
      value: '',
    },
    value: {
      type: Boolean,
      value: false,
    },
    disabled: {
      type: Boolean,
      value: false,
    },
    sticky: {
      type: Boolean,
      value: false,
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    isExpand: false,
  },

  /**
   * 组件的数据监听
   */
  observers: {
    value(value) {
      this.setData({
        isExpand: value
      })
    }
  },

  /**
   * 组件的生命周期
   */
  lifetimes: {
    created() {
      Object.defineProperty(this, 'parent', {
        get: () => this.getRelationNodes(path)[0],
      });
    },
    attached: function () {},
    detached: function () {},
  },

  /**
   * 组件的方法列表
   */
  methods: {
    onClick(e) {
      if (this.data.disabled) {
        return;
      }
      const {
        name,
        isExpand
      } = this.data;
      if (this.parent) {
        const {
          children = []
        } = this.parent;
        const index = children.indexOf(this);
        const currentName = String(name ? name : index);
        this.parent.switch(currentName, !isExpand);
      } else {
        this.triggerEvent('change', !isExpand)
      }
    },
    updateExpanded() {
      if (!this.parent) {
        return;
      }
      const {
        current,
        accordion
      } = this.parent.data;
      const {
        children = []
      } = this.parent;
      const {
        name
      } = this.data;
      const index = children.indexOf(this);
      const currentName = String(name ? name : index);
      const isExpand = accordion ? current[0] === currentName : (current || []).some((name) => name === currentName);
      this.setData({
        isExpand
      });
    },
  }
})